package com.huike.framework.security.handle;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.huike.common.core.domain.model.LoginUser;
import com.huike.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

// java example
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter("createTime")) {
            this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        }

        if (metaObject.hasSetter("createBy")) {
            // 自动填充创建人
            this.strictInsertFill(metaObject, "createBy", String.class, String.valueOf(getLoginUser()));
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter("updateTime")) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }

        if (metaObject.hasSetter("updateBy")) {
            this.setFieldValByName("updateBy", String.valueOf(getLoginUser()), metaObject);
        }

    }

    public Long getLoginUser() {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        if (loginUser != null) {
            return loginUser.getUser().getUserId();
        }
        return 1L;
    }
}